const passport = require('passport')
const Token = require('../models/token')
const JWTStrategy = require('passport-jwt').Strategy
const ExtractJWT = require('passport-jwt').ExtractJwt
const process = require('node:process')

passport.use(
  'refresh',
  new JWTStrategy(
    {
      secretOrKey: process.env.SECRET_KEY,
      jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
    },
    async (jwt_payload, done) => {
      try {
        const token = await Token.findOne({device: jwt_payload.deviceId})
        if (token) {
          const user = jwt_payload.user
          return done(null, user)
        } else {
          return done(null, false)
        }
      } catch (err) {
        return done(err, false)
      }
    },
  ),
)

module.exports = passport
